package com.judian.smart.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.blankj.utilcode.util.ObjectUtils;
import com.judian.smart.R;
import com.judian.smart.base.MyApplication;
import com.judian.smart.factory.GateWayFactory;
import com.judian.smart.interfaces.CameraHandleListener;
import com.judian.smart.interfaces.DevicePramsListener;
import com.judian.smart.interfaces.DeviceStatusListener;
import com.judian.smart.interfaces.GateWayListener;
import com.judian.smart.interfaces.SnapShotListener;
import com.judian.smart.model.GateWay;
import com.judian.smart.net.TcpSender;
import com.judian.smart.netty.NettySocketClient;
import com.judian.smart.proxy.WidgetDAOProxy;
import com.judian.smart.receiver.ReceiverBroadcast;
import com.judian.smart.socket.ISocketCode;
import com.judian.smart.util.ProjectUtils;
import com.judian.smart.util.RAKParams;
import com.judian.smart.util.SystemInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class GateWayService extends Service implements DeviceStatusListener, DevicePramsListener, SnapShotListener, GateWayListener {
    public static final String TAG = GateWayService.class.getSimpleName();
    String stata = "";
    int gatewayIndex = 0;
    public static long userid;
    public static List<GateWay> list = new ArrayList<>();
    public static List<String> list_userid = new ArrayList<>();
    public static List<String> link_userid = new ArrayList<>();
    public static Map<String, String> mp = new HashMap<>();
    private static CameraHandleListener cameraHandleListener = null;
    private static GateWayService instance;
    public static int[] serial = new int[200];

    public static GateWayService getInstance() {
        if (null == instance) {
            instance = new GateWayService();
        }
        return instance;
    }

    @Override
    public IBinder onBind(Intent intent) {
        instance = this;
        ReceiverBroadcast.setListener(this);
        return new CameraBinder();
    }


    public class CameraBinder extends Binder {
        public void startFindDevice() {
            try {
                Log.d("网关", "开启网关服务");
                init();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void stopFindDevice() {

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    //yyx 删除list中的网关时删除错误的网关，导致这里的mp的数据不对称得不到对应的userid 已修改
                    Log.d("yyx Camera", "stopFindDevice: " + list.get(i).getGatewayID());
                }
                list.clear();
                list_userid.clear();
                link_userid.clear();
                mp.clear();
            }
        }

    }

    public static void setCameraHandleListener(
            CameraHandleListener cameraHandleListener) {
        GateWayService.cameraHandleListener = cameraHandleListener;
    }

    private void init() {
        list.clear();
        list_userid.clear();
        link_userid.clear();
        mp.clear();
        List<GateWay> sqlList = GateWayFactory.getInstance().getAll();
        Log.d("网关", "数据库中网关数量 ->" + sqlList.size());

        for (GateWay gateWay : sqlList) {
            Log.d("网关", "数据库中网关 ->" + gateWay);
        }
        if (sqlList.size() > 0) {
            for (int i = 0; i < sqlList.size(); i++) {
                GateWay tempWay = sqlList.get(i);
                String wayName = tempWay.getGatewayName();
                final String did = tempWay.getGatewayID();
                final String userName = tempWay.getUserName();
                final String passWord = tempWay.getUserPassWord();
                int typeID = tempWay.getTypeId();
                int isCurrent = tempWay.getIsCurrent();
                mp.put(did, userid + "");
                list_userid.add(userid + "");
                if (typeID <= 3) {
                    if (SystemInfo.getSSID(MyApplication.getInstance()).startsWith("RAK")) {
                        if (typeID == 1) {
                            String resultStr = RAKParams.getParams("Connect", did, 100);
                            MyApplication.getInstance().sendBroadCast(resultStr);
                        } else {
                            String resultStr = RAKParams.getParams("Connect", did, 9);
                            MyApplication.getInstance().sendBroadCast(resultStr);
                        }
                    } else {
                        String result = ISocketCode.setConnect(did, userName,
                                passWord, isCurrent);
//                        MainActivity.mInstance.sendCode(result);
                        NettySocketClient.getInstans().sendData(result);
                    }
                    if (isCurrent == 1) {
                        ProjectUtils.getRootPath().setRootID(did);
                        ProjectUtils.saveRootPath();
                    }
                }
                Log.d("网关", "添加网关");
                GateWay gateWay = new GateWay();
                gateWay.setId(tempWay.getId());
                gateWay.setUserid((int) userid);
                gateWay.setGatewayName(wayName);
                gateWay.setState(getString(R.string.gateLink));
                gateWay.setUserName(userName);
                gateWay.setGatewayID(did);
                gateWay.setUserPassWord(passWord);
                gateWay.setTypeId(typeID);
                gateWay.setIsCurrent(isCurrent);
                gateWay.setPicData(tempWay.getPicData());
                list.add(gateWay);
            }
            Log.d(TAG, "init: !!!!!!!!!!!!!!! 网关列表数目 ->" + list.size());
        }
        handler.sendEmptyMessage(2);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                stata = "";
                switch (msg.arg1) {
                    case 0:
                        TcpSender.isGateWay = false;
                        stata = getString(R.string.gateLink);
                        break;
                    case 1:
                        TcpSender.isGateWay = true;
                        stata = getString(R.string.gateUserError);
                        break;
                    case 2:
                        stata = getString(R.string.gateUserCount);
                        break;
                    case 3:
                        stata = getString(R.string.gateStream);
                        break;
                    case 4:
                        stata = getString(R.string.videoLose);
                        break;
                    case 5:
                        TcpSender.isGateWay = false;
                        stata = getString(R.string.gateInvalidId);
                        break;
                    case 6:
                        break;
                    case 7:
                        break;
                    case 8:
                        stata = getString(R.string.gateLinkLose);
                        break;
                    case 9:
                        TcpSender.isGateWay = true;
                        stata = getString(R.string.gateWayUnLine);
                        break;
                    case 10:
                        stata = getString(R.string.gateLinkPass);
                        break;
                    case 11:
                        stata = getString(R.string.lose);
                        break;
                    case 12:
                        stata = getString(R.string.checkuser);
                        break;
                    case 101:
                        stata = getString(R.string.gateLinkError);
                        break;
                    case 100:
                        TcpSender.isGateWay = true;
                        stata = getString(R.string.gateWayLine);
                        break;
                }
                Log.d(TAG, "handleMessage: 网关状态：" + stata);
                if (stata.equals(getString(R.string.gateWayUnLine))) {
                    sendBroadcast(new Intent("GateWayIsLineReceiver").putExtra("gateway_connect", false));
                }
                // 判断网关在线问题
                for (int i = 0; i < list_userid.size(); i++) {
                    int getid = Integer.parseInt(list_userid.get(i));
                    if (msg.arg2 == getid) {
                        if (list == null || i >= list.size()) {
                            break;
                        }
                        GateWay gateWay = list.get(i);
/*                        gateWay.setState(stata);
                        Log.d(TAG, "handleMessage: 网关设定情况 ->" + gateWay);*/
                        if (!gateWay.getState().equals(stata)) {
                            if (cameraHandleListener != null) {
                                cameraHandleListener.changeList();
                            }
                        }
                    }
                }
                GateWay gateWay = list.get(gatewayIndex);
                gateWay.setState(stata);
                Log.d(TAG, "handleMessage: 网关设定情况 ->" + gateWay);
                gatewayIndex++;
                if (gatewayIndex >= list.size()) {   //网关大于或等于网关列表数目说明又一次网关轮回
                    gatewayIndex = 0;   //网关下标清零
                    Log.d(TAG, "handleMessage: -------------------------------------");
                }
            } else if (msg.what == 1) {
                if (list != null && list.size() > 0) {
                    if (list.size() == list_userid.size()) {
                        for (int i = 0; i < list_userid.size(); i++) {
                            int getid = Integer.parseInt(list_userid.get(i));
                            if (msg.arg2 == getid) {
                                link_userid.remove(getid + "");
                                link_userid.add(getid + "");
                                GateWay cb = list.get(i);
                                cb.setPicData((Drawable) msg.obj);
                                if (cameraHandleListener != null) {
                                    cameraHandleListener.changeList();
                                }
                            }
                        }
                    } else {
                        init();

                    }
                }
            } else if (msg.what == 2) {
                for (int j = 0; j < list.size(); j++) {
                    GateWay gateWay = list.get(j);
                    if (gateWay.getTypeId() < 3) {
                        gateWay.setState(getString(R.string.gateLink));
                        String deviceID = SystemInfo.getMasterID(MyApplication.getInstance());
                        if (SystemInfo.getSSID(MyApplication.getInstance()).startsWith("RAK")) {
                            if (gateWay.getTypeId() == 1) {
                                String resultStr = RAKParams.getParams("Connect", gateWay.getUserName(), 100);
                                MyApplication.getInstance().sendBroadCast(resultStr);
                            } else {
                                String resultStr = RAKParams.getParams("Connect", gateWay.getUserName(), 9);
                                MyApplication.getInstance().sendBroadCast(resultStr);
                            }
                        } else {
                            String result = ISocketCode.setConnect(
                                    gateWay.getGatewayID(), gateWay.getUserName(),
                                    gateWay.getUserPassWord(),
                                    gateWay.getIsCurrent());
//                            MainActivity.mInstance.sendCode(result);
                            NettySocketClient.getInstans().sendData(result);
                        }
                    }
                    if (cameraHandleListener != null) {
                        cameraHandleListener.changeList();
                    }
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void getSnapShot(long UserID, byte[] nType, int len) {
        try {
            BitmapDrawable drawable = new BitmapDrawable(
                    BitmapFactory.decodeByteArray(nType, 0, len));
            Message msg = handler.obtainMessage(1, 1, (int) UserID);
            msg.obj = drawable;
            handler.sendMessage(msg);
        } catch (Exception exception) {
        }
    }

    @Override
    public void getDevicePrams(long UserID, long nType, String param) {
        try {
            for (int i = 0; i < list_userid.size(); i++) {
                int getid = Integer.parseInt(list_userid.get(i));
                if (UserID == getid) {
                    if (nType == 10022) {
                        if (param.endsWith("")) {
                            List<GateWay> gateWayList = GateWayService.list;
                            for (GateWay gateway : gateWayList) {
                                if (gateway.getTypeId() == 200) {
                                    long userId = Integer
                                            .parseInt(GateWayService.mp.get(gateway.getGatewayID()));
                                    if (userId == UserID) {
                                        //&& (gateway.getIsCurrent() > 0)) {
                                        if (param.startsWith("DST")) {
                                            return;
                                        }
                                        int nowSerial = Integer.valueOf(
                                                param.substring(2, 4), 16);
                                        if (serial[(int) UserID] != nowSerial) {
                                            serial[(int) UserID] = nowSerial;
                                            String cmd = param.substring(0, param.length() - 1);
                                            String result = "{\"MasterID\":\"" + gateway.getGatewayID() + "\",\"ToID\":\"000000\",\"MsgType\":\"Response\",\"MsgState\":1,\"Content\":\"" + cmd + "\"}";
                                            ReceviceBroadcast(result);
                                            //TcpSender.dataProcess(cmd);

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void receiveDeviceStatus(long userid, int status) {
        if (list_userid != null && list_userid.size() > 0) {
            for (int i = 0; i < list_userid.size(); i++) {
                int getid = Integer.parseInt(list_userid.get(i));
                if (userid == getid) {
                    if (list == null || i >= list.size()) {
                        break;
                    }
                    GateWay cb = list.get(i);
                    if (cb.getTypeId() == 200) {
                        Message msg = handler.obtainMessage(0, status, (int) userid);
                        handler.sendMessage(msg);
                    }
                    break;
                }
            }
        }

    }

    @Override
    public void receiveGateWayStatus(int type, long userid, int status, String contant) {
        if (type == 1) {
            if (list_userid != null && list_userid.size() > 0) {
                for (int i = 0; i < list_userid.size(); i++) {
                    int getid = Integer.parseInt(list_userid.get(i));
                    if (userid == getid) {
                        if (list == null || i >= list.size()) {
                            break;
                        }
                        GateWay cb = list.get(i);
                        if (cb.getTypeId() < 3) {
                            String ip = "";
                            if (contant.contains("(") && contant.contains(")")) {
                                ip = contant.split("\\(")[1].split("\\)")[0];
                            }
                            cb.setStateCode(status);
                            if (!ObjectUtils.equals(ip, cb.getData1()) && status == 100) {
                                cb.setData1(ip);
                                int num = WidgetDAOProxy.getInstance().getWidgetDataBase().updateGateWay(cb, cb.getGatewayName());
                            }
                            Message msg = handler.obtainMessage(0, status, (int) userid);
                            handler.sendMessage(msg);
                        }
                        break;
                    }
                }
            }
        } else if (type == 1) {
            Message msg = handler.obtainMessage(0, status, (int) userid);
            handler.sendMessage(msg);
        }
    }


    public static List<GateWay> getList() {
        List<GateWay> gateWayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getTypeId() < 3) {
                gateWayList.add(list.get(i));
            }
        }
        return gateWayList;
    }


    public void ReceviceBroadcast(String result) {
        Log.e("cmdCode", result);
        Intent intent = new Intent("com.zunder.smart.receiver");
        Bundle bundle = new Bundle();
        bundle.putString("str", result);
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }


    public List<GateWay> getGatewayList() {
        List<GateWay> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GateWay gateWay = list.get(i);
            if (gateWay.getTypeId() <= 3) {
                result.add(gateWay);
            }
        }
        return result;
    }
}
